package Sort.sort2020;

/**
 * @author leiwenkang
 * @date 2020/3/29
 */
public class BubbleSort {

    public static void main(String[] args) {
        int[] array = {3,8,4,6,7,2,5,9,1};
        bubbleSort(array);
        for (int i = 0; i < array.length; i++){
            System.out.print(array[i]);
            System.out.print(" ");
        }
    }

    //交换排序
    public static void bubbleSort(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }

        for (int i = 0; i < array.length - 1; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < array[i]) {
                    //交换
                    int temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
                }
            }
        }
    }

    //真正的冒泡排序
    public static void bubbleSort2(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }

        boolean flag = true;
        for (int i = 0; i < array.length - 1 && flag; i++) {
            flag = false;
            for (int j = array.length - 1; j >= i + 1; j--) {
                if (array[j] < array[j - 1]) {
                    //交换
                    int temp = array[j];
                    array[j] = array[j- 1];
                    array[j - 1] = temp;
                    flag = true;
                }
            }
        }
    }
}
